﻿using Qy.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class LogService : QyRepository<LogSql>
{
    public LogService(ApplicationContext applicationContext) : base(applicationContext)
    {
    }

    /// <summary>
    /// 获取全部列表
    /// </summary>
    public async Task<PagedInfo<ViewLogSql>> GetSqlListAsync(LogSqlQuery parm)
    {
        DateTime startDate = DateUtility.GetBeginTime(parm.StartDate, -1);
        DateTime endDate = DateUtility.GetBeginTime(parm.EndDate, 1);
        Expressionable<LogSql> exp = Expressionable.Create<LogSql>();
        exp = exp.AndIF(parm.Uid != 0, data => data.UserId == parm.Uid);
        exp = exp.AndIF(parm.StartDate != null && parm.EndDate != null, data => data.Time >= startDate && data.Time <= endDate);
        return await Queryable()
            .LeftJoin<User>((data, user) => data.UserId == user.Id)
            .LeftJoin<UserDept>((data, user, dept) => user.DeptId == dept.Id)
            .Where(exp.ToExpression())
            .WhereIF(!string.IsNullOrEmpty(parm.NickName), (data, user) => user.NickName.Contains(parm.NickName))
            .OrderBy((data) => data.Id, OrderByType.Desc)
            .Select((data, user, dept) => new ViewLogSql()
            {
                Id = data.Id.SelectAll(),
                NickName = user.NickName,
                DeptName = dept.Name
            })
            .ToPageAsync(parm);
    }
    /// <summary>
    /// 获取用户ID列表指定条数
    /// </summary>
    public async Task<List<ViewLogSql>> GetListAsync(int uid, int limit)
    {
        return await Queryable()
            .Where(data => data.UserId == uid)
            .Take(limit)
            .OrderBy(data => data.Id, OrderByType.Desc)
            .Select(data => new ViewLogSql()
            {
                Id = data.Id.SelectAll()
            })
            .ToListAsync();
    }
    public bool Clear()
    {
        return Context.DbMaintenance.TruncateTable<LogSql>();
    }


    public async void InsertLogAsync(LogSql logSql)
    {
        await InsertAsync(logSql);
    }
}
